package es

import (
	"context"
	"easyblog/models"
	"easyblog/utils/errmsg"
	"easyblog/utils/log"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"strconv"
)

func parseArticle(article *models.Article) esArticle{
	return esArticle{
		ID : 		int(article.ID),
		Title: 		article.Title,
		Desc :    	article.Desc,
		Content :  	article.Content,
		CreateTime: article.UpdatedAt,
	}
}

func CreateArticle(article *models.Article){

	if !esEnable {
		return
	}

	esarticle := parseArticle(article)

	ctx := context.Background()
	_, err := EsClient.Index().
		Index(esIndex).
		Id(strconv.Itoa(esarticle.ID)).
		BodyJson(esarticle).
		Do(ctx)

	if err != nil {
		log.Logger.Error("article create ES err",err.Error())
	}
}

func EditArticle(article *models.Article){

	if !esEnable {
		return
	}

	esarticle := parseArticle(article)

	ctx := context.Background()
	_, err := EsClient.Update().
		Index(esIndex).
		Id(strconv.Itoa(esarticle.ID)).
		Doc(esarticle).
		Do(ctx)

	if err != nil {
		log.Logger.Error("article update ES err",err.Error())
	}
}

func DeleteArticle(articleId int){

	if !esEnable {
		return
	}

	ctx := context.Background()
	_, err := EsClient.Delete().
		Index(esIndex).
		Id(strconv.Itoa(articleId)).
		Do(ctx)

	if err != nil {
		log.Logger.Error("article delete ES err",err.Error())
	}
}

func SearchArticle(keyWords string)([]int, int ){

	if !esEnable {
		return nil,errmsg.ERROR
	}

	var ids []int

	ctx := context.Background()
	fsc := elastic.NewFetchSourceContext(true).Include("ID")

	query := elastic.NewBoolQuery()
	query.Should(elastic.NewTermsQuery("Title", keyWords))
	query.Should(elastic.NewTermsQuery("Desc", keyWords))
	query.Should(elastic.NewTermsQuery("Content", keyWords))

	searchResult, err := EsClient.Search().
		Index(esIndex).
		Query(query).
		FetchSourceContext(fsc).
		Pretty(true).
		Do(ctx)

	if err != nil {
		log.Logger.Error("article search ES err",err.Error())
		return nil,errmsg.ERROR
	}

	if searchResult.TotalHits() > 0 {
		for _, hit := range searchResult.Hits.Hits {
			var t esArticle
			json.Unmarshal(hit.Source, &t)
			ids = append(ids, t.ID)
		}
	}
	return ids,errmsg.SUCCSE
}